import {http} from "./http";
import {createPlainAddressService, eAddressTypeEnum, i18n, iAddressSyncMeta, iPlainAddressData} from "plain-design";
import {pathJoin} from '@peryl/utils/pathJoin';
import {microApp} from "../../microApp";

export const address = createPlainAddressService({
  http,
  getAddress: async () => {
    const resp = await fetch(pathJoin(microApp.baseAssetsPublicPath.get(), i18n.state.currentLang === 'zh-cn' ? 'data/address_zhcn.json' : 'data/address_enus.json'));

    let list = await resp.json();

    /*const pinyin = await microApp.resource.load('pinyin', window);*/
    /*const formatPinyin = (item: any) => {
      return {
        ...item,
        name: (() => {
          let _name: [string][] = pinyin(item.name, { style: pinyin.STYLE_NORMAL });
          if (_name[_name.length - 1][0] === 'sheng') {
            _name = _name.slice(0, -1);
          }
          return _name.map(i => i[0].charAt(0).toUpperCase() + i[0].slice(1)).join('');
        })(),
        ...!item.children ? {} : {
          children: item.children.map((i: any) => formatPinyin(i))
        }
      };
    };

    list = list.map((i: any) => formatPinyin(i))

    console.log(JSON.stringify(list))*/

    const format = (list: iPlainAddressData[]): iAddressSyncMeta[] => {
      return list.map(i => ({
        label: i.name,
        code: i.code,
        type: (Deep2Type as any)[i.deep],
        parentCode: i.parentCode,
        ...!i.children ? {} : { children: format(i.children) },
      }));
    };

    return format(list as any);
  }
});

const Deep2Type = {
  0: eAddressTypeEnum.province,
  1: eAddressTypeEnum.city,
  2: eAddressTypeEnum.district,
} as const;
